package m.common.action;

import m.system.RuntimeData;
import m.system.exception.MException;
import m.system.util.FileUtil;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;

import java.io.File;
import java.io.InputStream;

public class HtmlPageResult extends HtmlResult {
    private JSONMessage param;
    private String url;
    public HtmlPageResult(String url){
        this(url,new JSONMessage());
    }
    private HtmlPageResult(String url,JSONMessage param) {
        this.url="/"+url;
        this.param=param;
    }
    public HtmlPageResult addParam(String name,Object value){
        this.param.push(name,value);
        return this;
    }
    public JSONMessage getParam() {
        return param;
    }
    public void setParam(JSONMessage param) {
        this.param = param;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    @Override
    public String outHtml() {
        String txt;
        try {
            File file;
            if(FileUtil.existsWebFile(this.url)) {//寻找web目录下文件
                file=new File(RuntimeData.getClassWeb()+this.url);
            }else if(FileUtil.existsPublicFile(this.url)) {//寻找web目录下文件
                file=new File(RuntimeData.getPublicWeb()+this.url);
            }else {//不存在则找临时目录
                String ps=RuntimeData.getClassTmp()+this.url;
                file=new File(ps);
                if(!file.exists()) {
                    InputStream is=this.getClass().getClassLoader().getResourceAsStream("web"+this.url);
                    if(null!=is) FileUtil.writeFile(ps, is);
                    file=new File(ps);
                }
            }
            txt=FileUtil.read(file).trim();
            return "<script>var param=" + param + "</script>" +
                    txt;
        } catch (Exception e) {
            try {
                return ObjectUtil.toString(param);
            } catch (MException ex) {
                return "{}";
            }
        }
    }

    @Override
    public String getContent() {
        return new JSONMessage().push("url",url).push("param",param).toJSONString();
    }
}
